package cn.edu.scau.sec.rw.model.disk_file.utils;

import cn.edu.scau.sec.rw.model.disk_file.disk.Disk;
import cn.edu.scau.sec.rw.model.disk_file.file.FileCatalog;
import cn.edu.scau.sec.rw.model.disk_file.file.VirtualFile;

/**
 * 文件（夹）——磁盘操作工具类
 */
public class File_DiskUtil {

    private static Disk disk = Disk.getDisk();

    /**
     * 保存文件
     * @param virtualFile
     */
    public static void saveVirtualFile(VirtualFile virtualFile){

        for (int i = 0; i < disk.getFAT().length; i++) {
            if (disk.getFAT()[i] == 0) {
//                System.out.println("setStart" + i);
                virtualFile.setStart(i);
                System.out.println("start" + virtualFile.getName() + " " + i);
                disk.getFAT()[i] = -1;
                break;
            }
        }
        int bytes = virtualFile.getBytes() - 64;

        int index = virtualFile.getStart();
        int index2 = index+1;

        while (index2 < disk.getFAT().length && bytes > 0){

            if (disk.getFAT()[index2] == 0){
                disk.getFAT()[index] = index2;
                disk.getFAT()[index2] = -1;
                index = index2;
                bytes -= 64;
            }
//            System.out.println(index2);
            index2++;
        }

        if (index2 == disk.getFAT().length) System.out.println("磁盘已满！！");
    }

    /**
     * 删除文件
     * @param virtualFile
     */
    public static void deleteVirtualFile(VirtualFile virtualFile){
        deletePattern(virtualFile);
        if (virtualFile instanceof FileCatalog && ((FileCatalog) virtualFile).getChild().size() != 0){
            for (VirtualFile file : ((FileCatalog) virtualFile).getChild()) {
                deleteVirtualFile(file);
            }
        }
    }

    private static void deletePattern(VirtualFile virtualFile){
//        System.out.println("删除");
        int[] diskFAT = disk.getFAT();
        int index = virtualFile.getStart();
//        System.out.println("begin"+index);
        while (diskFAT[index] != -1){
            int temp = diskFAT[index];
            diskFAT[index] = 0;
            index = temp;
//            System.out.println(index);
        }
        diskFAT[index] = 0;
//        for (int i = 0; i < disk.getFAT().length; i++) {
//            System.out.print(disk.getFAT()[i]);
//        }

        for (int i : disk.getFAT()) {
            System.out.print(i+" ");
        }
        System.out.println();
    }
}
